//
//  CommonTools.m
//  housekeep
//
//  Created by ttouch on 16/5/8.
//  Copyright © 2016年 谭真. All rights reserved.
//

#import "CommonTools.h"
#import "math.h"

@implementation CommonTools

#pragma mark - 应用信息

+ (NSString *)appDisplayName {
    NSString *appDisplayName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleDisplayName"];
    if (!appDisplayName) appDisplayName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];
    return appDisplayName;
}

+ (NSString *)appBundleName {
    return [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];
}

+ (NSString *)appVersion {
    NSString *version = [NSString stringWithFormat:@"%@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
    return version;
}

+ (BOOL)needShowNewFeature {
    NSString *lastVersion = [mUserDefaults objectForKey:@"lastVersion"];
    if (!lastVersion || ![lastVersion isEqualToString:[self appVersion]]) {
        [mUserDefaults setObject:[self appVersion] forKey:@"lastVersion"];
        [mUserDefaults synchronize];
        return YES;
    }
    return NO;
}

#pragma mark - 文本计算

/// 计算文字size
+ (CGSize)sizeOfText:(NSString *)text fontSize:(CGFloat)fontSize {
    return [self sizeOfText:text fontSize:fontSize width:CGFLOAT_MAX height:5000];
}

+ (CGSize)sizeOfText:(NSString *)text fontSize:(CGFloat)fontSize width:(CGFloat)width {
    return [self sizeOfText:text fontSize:fontSize width:width height:5000];
}

+ (CGSize)sizeOfText:(NSString *)text fontSize:(CGFloat)fontSize width:(CGFloat)width height:(NSInteger)height {
    CGSize size = [text boundingRectWithSize:CGSizeMake(width, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil].size;
    return size;
}
+(CGSize)sizeWithText:(NSString *)text font:(CGFloat)font {
    CGSize size = [text boundingRectWithSize:CGSizeMake(mScreenWidth - 30, CGFLOAT_MAX) options:
                       NSStringDrawingUsesLineFragmentOrigin |
                       NSStringDrawingUsesFontLeading
                                         attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil].size;
    return size;
}
#pragma mark - 正则验证
//允许汉字，大小写或数字(不限字数)
+(BOOL)inputChineseOrLettersAndNumbersNum:(NSString*)string {
    
    NSString *regex = @"[a-zA-Z\u4e00-\u9fa5][a-zA-Z0-9\u4e00-\u9fa5]+";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    BOOL  inputString = [predicate evaluateWithObject:string];
    return inputString;
}
+(BOOL)inputShouldLetterOrNum:(NSString *)inputString {
    if (inputString.length == 0) return NO;
    NSString *regex =@"[a-zA-Z0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:inputString];
}

//判断是否含有非法字符 yes 有  no没有
+ (BOOL)JudgeTheillegalCharacter:(NSString *)content {
    NSString *regex = @"[^a-zA-Z0-9\u4E00-\u9FA5,.?:;()!{}<>#*-+=，。、？：；（）！{}+=]➋➌➍➎➏➐➑➒";
    NSRange urgentRange = [content rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString: regex]];
    if (urgentRange.location == NSNotFound) {
        return NO;
    }
    return YES;
}
/// 是否是身份证
+ (BOOL)validateIdentityCard: (NSString *)identityCard {
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}

/// 是否是手机号
+ (BOOL)isMobileNumber:(NSString *)mobileNum {
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188,183
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189,177
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-9]|8[0-9]|7[0-9])\\d{8}$";
    NSString * CM = @"^1(34[0-9]|(3[0-9]|5[0-9]|8[0-9])\\d)\\d{7}$";
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    NSString * CT = @"^1((33|53|8[09]|77)[0-9]|349)\\d{7}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm     = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu     = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct     = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    return (([regextestmobile evaluateWithObject:mobileNum]) || ([regextestcm evaluateWithObject:mobileNum]) || ([regextestct evaluateWithObject:mobileNum]) || ([regextestcu evaluateWithObject:mobileNum]));
}

/// 是否是邮箱
+ (BOOL)isEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

/// 是否是QQ
+ (BOOL)isQqNumber:(NSString *)qqNum {
    NSString *qqstr = @"[1-9][0-9]{4,}";
    NSPredicate *qqTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",qqstr];
    return [qqTest evaluateWithObject:qqNum];
}

/// 是否是银行卡
+ (BOOL)isBankCardNumber: (NSString *)bankCardNumber {
    BOOL flag;
    if (bankCardNumber.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{15,30})";
    NSPredicate *bankCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [bankCardPredicate evaluateWithObject:bankCardNumber];
}

#pragma mark - 颜色相关

/// 返回随机颜色
+ (UIColor *)colorLightRandom {
    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 );  //  0.5 to 1.0, away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}

/// 以UIColor生成一张UIImage
+ (UIImage *)imageCreateWithColor:(UIColor *)color {
    return [self imageCreateWithColor:color size:CGSizeMake(1.0, 1.0)];
}

+ (UIImage *)imageCreateWithColor:(UIColor *)color size:(CGSize)size {
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

#pragma mark - 图片相关

/// 压缩图片尺寸,方便上传服务器
+ (UIImage *)imageScale:(UIImage *)img size:(CGSize)size{
    if (img.size.width <= size.width) {
        return img;
    }
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

#pragma mark - 时间戳 <-> 时间字符串 转换

/// 时间戳 -> 时间字符串 dateFormat默认为yyyy-MM-dd
+ (NSString *)getTimeStrBytimeStamp:(NSString *)timeStamp {
    return [self getTimeStrBytimeStamp:timeStamp dateFormat:@"yyyy/MM/dd"];
}

+ (NSString *)getTimeStrBytimeStamp:(NSString *)timeStamp dateFormat:(NSString *)dataFormat {
    if (![CommonTools isNotNull:timeStamp]) return @"";
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:dataFormat];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timeStamp doubleValue]];
    if (!date) return @"";
    NSString *dateString = [formatter stringFromDate:date];
    return dateString ? dateString : @"";
}
+ (NSString *)getTimeStrBytimeSt:(NSString *)timeStamp {
    return [self getTimeStrBytimeStamp:timeStamp dateFormat:@"yyyy/MM/dd HH:mm:ss"];
}

/// 时间字符串 -> 时间戳 dateFormat默认为MM-dd
+(NSString *)getTimeMothWithDayStr:(NSString *)timeStr{
    return [self getTimeStrBytimeStamp:timeStr dateFormat:@"MM月dd日 HH:mm"];
}

+ (NSString *)strWithTimestamp:(long long)timestamp {
    NSDate *msgDate = [NSDate dateWithTimeIntervalSince1970:timestamp / 1000.0];
    NSDateFormatter *dateFmt = [[NSDateFormatter alloc] init];
    [dateFmt setDateFormat:@"MM/dd HH:mm"];
    
    return [self formateDate:[dateFmt stringFromDate:msgDate]];
}

+ (NSString *)formateDate:(NSString *)dateString
{
    @try {
        // ------实例化一个NSDateFormatter对象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MM/dd HH:mm"];//这里的格式必须和DateString格式一致
        
        NSDate * nowDate = [NSDate date];
        
        // ------将需要转换的时间转换成 NSDate 对象
        NSDate * needFormatDate = [dateFormatter dateFromString:dateString];
        if (!needFormatDate) {
            return dateString;
        }
        // ------取当前时间和转换时间两个日期对象的时间间隔
        NSTimeInterval time = [nowDate timeIntervalSinceDate:needFormatDate];
        
        // ------再然后，把间隔的秒数折算成天数和小时数：
        
        NSString *dateStr = [[NSString alloc] init];
        
        if (time<=60) {  //1分钟以内的
            
            dateStr = @"刚刚";
            
        }else if(time<=60*60){  //一个小时以内的
            
            int mins = time/60;
            dateStr = [NSString stringWithFormat:@"%d分钟前",mins];
            
        }else if(time<=60*60*24){  //在两天内的
            
            [dateFormatter setDateFormat:@"YYYY-MM-dd"];
            NSString * need_yMd = [dateFormatter stringFromDate:needFormatDate];
            NSString *now_yMd = [dateFormatter stringFromDate:nowDate];
            
            [dateFormatter setDateFormat:@"HH:mm"];
            if ([need_yMd isEqualToString:now_yMd]) {
                //在同一天
                dateStr = [NSString stringWithFormat:@"今天 %@",[dateFormatter stringFromDate:needFormatDate]];
            }else{
                //昨天
                dateStr = [NSString stringWithFormat:@"昨天 %@",[dateFormatter stringFromDate:needFormatDate]];
            }
        } else {

            [dateFormatter setDateFormat:@"yyyy"];
            NSString * yearStr = [dateFormatter stringFromDate:needFormatDate];
            NSString *nowYear = [dateFormatter stringFromDate:nowDate];
            
            if ([yearStr isEqualToString:nowYear]) {
                //在同一年
                [dateFormatter setDateFormat:@"MM-dd"];
                dateStr = [dateFormatter stringFromDate:needFormatDate];
                return dateString;
            }else{
                [dateFormatter setDateFormat:@"MM-dd"];
                dateStr = [dateFormatter stringFromDate:needFormatDate];
                return dateString;
            }
        }
        
        return dateStr;
    }
    @catch (NSException *exception) {
        return @"";
    }
    
    
}



#pragma mark - 富文本字符串处理

/// 返回NSAttributedString，左侧String为灰色，右侧为kMainColor
+ (NSAttributedString *)getAttributedStringWithFirstString:(NSString *)firstStr firstColor:(UIColor *)firstColor lastString:(NSString *)lastStr lastColor:(UIColor *)lastColor fontSize:(CGFloat )fontSize {
    UIFont *font = [UIFont fontWithName:@"ZhaimiMedium-" size:fontSize];
    NSMutableAttributedString *p1 = [[NSMutableAttributedString alloc] initWithString:firstStr attributes:@{ NSFontAttributeName : font, NSForegroundColorAttributeName :firstColor }];
    NSMutableAttributedString *p2 = [[NSMutableAttributedString alloc] initWithString:lastStr attributes:@{ NSFontAttributeName : font, NSForegroundColorAttributeName :lastColor }];
    [p1 appendAttributedString:p2];
    return p1;
}

#pragma mark - 距离计算

/*
 2个坐标距离
 常用到如image1.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(335));
 CGAffineTransformMakeRotation中要填的是弧度，所以要转换一下。
 下面是两个宏，来实现互转
 1。弧度转角度
 #define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))
 NSLog(@”Output radians as degrees: %f”, RADIANS_TO_DEGREES(0.785398));
 2。角度转弧度
 // Degrees to radians
 #define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
 NSLog(@”Output degrees as radians: %f”, DEGREES_TO_RADIANS(45));
 M_PI 定义在Math.h内，其值为3.14159265358979323846264338327950288
 */
#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))
#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
+ (NSString *)locationWithLatitude:(NSString *)firstLatitude withLongitude:(NSString *)firstLongitude WithLatitude:(NSString *)secondLatitude withLongitude:(NSString *)secondLongitude {
    double firLat = [firstLatitude doubleValue];
    double secLat = [secondLatitude doubleValue];
    double firLng = [firstLongitude doubleValue];
    double secLng = [secondLongitude doubleValue];
    
    double theta = firLng - secLng;
    double miles = (sin(DEGREES_TO_RADIANS(firLat)) * sin(DEGREES_TO_RADIANS(secLat))) + (cos(DEGREES_TO_RADIANS(firLat)) * cos(DEGREES_TO_RADIANS(secLat)) * cos(DEGREES_TO_RADIANS(theta)));
    miles = acos(miles);
    miles = RADIANS_TO_DEGREES(miles);
    miles = miles * 60 * 1.1515;// 英里
    //    double feet = miles * 5280; // 英尺
    double kilometers = miles * 1.609344; // 千米
    kilometers = kilometers * 1000;
    kilometers = round(kilometers);
    NSString *milsStr = [NSString stringWithFormat:@"%0.f", kilometers];
    return milsStr;
}

#pragma mark - 其他

/// 防止nil，如果是nil,返回空字符串
+ (NSString *)avoidNil:(NSString *)str {
    if (!str) return @"";
    if ([str isEqualToString:@"(null)"]) return @"";
    return str;
}

/// 检查value是否为空，是空则返回NO,非空返回YES
+ (BOOL)isNotNull:(id)value {
    if (!value) return NO;
    if ([value isKindOfClass:[NSNull class]]) return NO;
    return YES;
}

+ (BOOL)hasLength:(id)value {
    if ([self isNotNull:value]) {
        if ([value isKindOfClass:[NSString class]]) {
            return [value length];
        }
        return YES;
    }
    return NO;
}

/// 判断文件夹是否存在
+ (BOOL)isExistFile:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
    if(!(isDirExist && isDir)) {
        return false;
    }
    return true;
}

/// 通用的警告框提示
+ (void)alertFormatofTitle:(NSString *)title withMessage:(NSString *)message withCancelBtnTitle:(NSString *)cancelTitle {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:cancelTitle otherButtonTitles:nil];
    [alert show];
}

+ (NSString *)getFirstLetterFromString:(NSString *)aString
{
    if (aString.length<=0) {
        return @"";
    }else {
        //转成了可变字符串
        NSMutableString *str = [NSMutableString stringWithString:aString];
        //先转换为带声调的拼音
        CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
        //再转换为不带声调的拼音
        CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
        //转化为大写拼音
        NSString *strPinYin = [str capitalizedString];
        //获取并返回首字母
        return [strPinYin substringToIndex:1];
    }
    
}

// 根据字符排版View
+ (CGFloat)configViewForStrViewArr:(NSMutableArray *)viewArr strArr:(NSArray *)strArr {
    CGFloat lblY = 0;
    CGFloat lblH = 20;
    CGFloat margin = 10;
    CGFloat loc = 0;
    CGFloat row = 0;
    CGFloat totalW = 0;
    for (int i = 0; i < viewArr.count; i ++) {
        UILabel *lbl = viewArr[i];
        CGFloat lblW = [self sizeOfText:strArr[i] fontSize:10].width + 20;
        CGFloat lblX = totalW;
        CGFloat supViewW = mScreenWidth -78;
        if ((lblX + lblW) > supViewW) {
            row += 1;
            loc = 0;
            lblX = 0;
            totalW = lblW +margin;
        } else {
            loc += 1;
            totalW += lblW + margin;
        }
        lblY = margin + (margin +lblH) *row;
        lbl.frame = CGRectMake(lblX, lblY, lblW, lblH);
    }
    return lblY + lblH +10;
}

// 设置Label行间距并自适应后取出高度
+ (CGFloat)configParagraphLbl:(UILabel *)lbl {
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:lbl.text];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.firstLineHeadIndent = 8; //首行缩进
    style.headIndent = 8; //缩进
    style.tailIndent = mScreenWidth -5; //尾部
    style.paragraphSpacing = 8;
    style.lineSpacing = 5;//行距
    style.alignment = NSTextAlignmentLeft;
    // 需要设置的范围
    NSRange range =NSMakeRange(0,lbl.text.length);
    [text addAttribute:NSParagraphStyleAttributeName value:style range:range];
    lbl.attributedText = text;
    [lbl sizeToFit];
    return lbl.height;
}



+(float)readCacheSize {
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES) firstObject];
    return [self folderSizeAtPath : cachePath];
}
+ (float)folderSizeAtPath:( NSString *) folderPath {
    
    NSFileManager * manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath :folderPath]) return 0 ;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator];
    NSString * fileName;
    long long folderSize = 0 ;
    while ((fileName = [childFilesEnumerator nextObject]) != nil ){
        //获取文件全路径
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
        folderSize += [self fileSizeAtPath :fileAbsolutePath];
    }
    
    return folderSize/( 1024.0 * 1024.0);
}


+(long long)fileSizeAtPath:( NSString *) filePath {
    NSFileManager * manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath :filePath]){
        return [[manager attributesOfItemAtPath :filePath error : nil] fileSize];
    }
    return 0;
}


//2. 清除缓存
+(NSString *)clearFile {
    NSString * cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
    NSArray * files = [[NSFileManager defaultManager ] subpathsAtPath :cachePath];
    for ( NSString * p in files) {
        NSError * error = nil ;
        //获取文件全路径
        NSString * fileAbsolutePath = [cachePath stringByAppendingPathComponent :p];
        
        if ([[NSFileManager defaultManager ] fileExistsAtPath :fileAbsolutePath]) {
            [[NSFileManager defaultManager ] removeItemAtPath :fileAbsolutePath error :&error];
        }
    }
    
    //读取缓存大小
    float cacheSize = [self readCacheSize] *1024;
    return [NSString stringWithFormat:@"%.2fMB",cacheSize];
}


//判断是否全是空格
+ (BOOL) isEmpty:(NSString *) str {
    if (!str) {
        return YES;
    } else {
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        if ([trimedString length] == 0) {
            return YES;
        } else {
            return NO;
        }
    }
}
@end
